// src/services/socketService.ts
import { io, Socket } from 'socket.io-client';

class SocketService {
  private socket: Socket;

  constructor(url: string) {
    this.socket = io(url, {
      path: '/your-custom-path/socket.io', // 自定义路径
      reconnection: true, // 启用重连
      reconnectionAttempts: Infinity, // 无限重连
      reconnectionDelay: 1000, // 重连延迟时间（毫秒）
    });
  }

  public connect() {
    this.socket.on('connect', () => {
      console.log('Socket connected:', this.socket.id);
    });

    this.socket.on('disconnect', (reason) => {
      console.log('Socket disconnected:', reason);
    });

    this.socket.on('reconnect', (attemptNumber) => {
      console.log('Reconnected after', attemptNumber, 'attempts');
    });
  }

  public onMessage(callback: (data: any) => void) {
    this.socket.on('message', callback);
  }

  public sendMessage(event: string, data: any) {
    this.socket.emit(event, data);
  }

  public disconnect() {
    this.socket.disconnect();
  }
}

export default SocketService;